package com.zcc.controller;

import com.zcc.dao.DepartmentDao;
import com.zcc.dao.EmployeeDao;
import com.zcc.pojo.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class EmployeeController {

    private final EmployeeDao employeeDao;

    public EmployeeController(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    @RequestMapping("/emps")
    public String list(Model model) {
        model.addAttribute("emps",new EmployeeDao().getALL());
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAdd(Model model) {
        model.addAttribute("departments", new DepartmentDao().getDepartments());
        return "emp/add";
    }

    @PostMapping("/emp")
    public String add(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/emp/{id}")
    public String toUpdate(@PathVariable int id,Model model) {
        model.addAttribute("emp",employeeDao.getEmployeeById(id));
        model.addAttribute("departments", new DepartmentDao().getDepartments());
        return "emp/update";
    }

    @PostMapping("/updateEmp")
    public String update(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/delEmp/{id}")
    public String delete(@PathVariable int id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
